﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

using SearchRS;
using NetworkServices;

namespace RapidSearcher
{
    public partial class RapidSearcher : Form, GUI
    {
        private bool isStopMode;
        private int rightClickRowId;
        private int rightClickColId;


        public RapidSearcher()
        {
            InitializeComponent();
            rapidShareResults.ClearSelection();
            isStopMode = false;
        }

        private void RapidSearcherButton_Click(object sender, EventArgs e)
        {
            if (isStopMode)
            {
                Program.SetStop();
                RapidSearcherButton.Enabled = false; // So user won't be able to search again until stop finished
            }
            else
            {
                rapidShareResults.Rows.Clear();
                Thread t = new Thread(Program.DoSearchAndAdd);
                t.Start(this);                
            }

            SetMode(!isStopMode);
        }

        private delegate void SetSearchEnabldeDelegate(bool enabled);
        public void SetSearchEnabled(bool enabled)
        {
            if (this.RapidSearcherButton.InvokeRequired)
            {
                SetSearchEnabldeDelegate SetSearchEnabledDelegate = SetSearchEnabled;
                this.Invoke(SetSearchEnabledDelegate, enabled);
            }
            else
            {
                RapidSearcherButton.Enabled = enabled;                
            }
        }

        private delegate void SetModeDelegate(bool isStop);
        public void SetMode(bool isStop)
        {
            if (this.RapidSearcherButton.InvokeRequired)
            {
                SetModeDelegate setModeDelegate = SetMode;
                this.Invoke(setModeDelegate, isStop);
            }
            else
            {
                isStopMode = isStop;

                if (isStopMode)
                {
                    RapidSearcherButton.Text = "Stop";
                }
                else
                {
                    RapidSearcherButton.Text = "Start";
                }                            
            }
        }

        public string GetSearchString()
        {
            return torecLink.Text;
        }

        public void SetStatusMessgeAndProgressAmount(string text, int amount)
        {
            toolStripStatusLabel.Text = text;

            if (statusStrip.InvokeRequired)
            {
                SetProgressBarValueDelegate setProgressBarValueDelegate = SetProgressBarValue;
                this.Invoke(setProgressBarValueDelegate, amount);
            }
            else
            {
                SetProgressBarValue(amount);
            }
        }

        private delegate void SetProgressBarValueDelegate(int value);
        void SetProgressBarValue(int value)
        {
            toolStripProgressBar.Value = (toolStripProgressBar.Maximum * value) / 100;
        }

        public bool SearchAppsAndGamesAndEbooksToo()
        {
            return searchGamesAndEbooks.Checked;
        }

        public bool SearchSubsSite()
        {
            return SearchSubSite.Checked;
        }

        private delegate int AddToListBox(ResultDetails resultDetails);

        public int AddResult(ResultDetails resultDetails)
        {
            if (this.rapidShareResults.InvokeRequired)
            {
                AddToListBox add = AddResult;
                return (int)this.Invoke(add, resultDetails);
            }
            else
            {
                string site = GetSiteName(resultDetails);
                int rowId = rapidShareResults.Rows.Add(resultDetails, site, resultDetails.Password);
                SetRowState(rowId, resultDetails.State);
                return rowId;
            }
        }

        private string GetSiteName(ResultDetails resultDetails)
        {
            string site = resultDetails.Url.Replace("http://www.", "").Replace("http://", "");
            site = site.Substring(0, site.IndexOf("."));
            TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;
            site = UsaTextInfo.ToTitleCase(site);
            return site;
        }

        private delegate void SetListBoxRowState(int rowId, ResultDetails resultDetails);
        public void UpdateResult(int rowId, ResultDetails resultDetails)
        {
            if (this.rapidShareResults.InvokeRequired)
            {
                SetListBoxRowState update = UpdateResult;
                this.Invoke(update, new object[] { rowId, resultDetails });
            }
            else
            {
                rapidShareResults.Rows[rowId].Cells[0].Value = resultDetails;
                rapidShareResults.Rows[rowId].Cells[1].Value = GetSiteName(resultDetails);
                rapidShareResults.Rows[rowId].Cells[2].Value = resultDetails.Password;
                SetRowState(rowId, resultDetails.State);
            }
            
        }

        private void SetRowState(int rowId, ResultState state)
        {
            DataGridViewCellStyle style = new DataGridViewCellStyle();

            switch (state)
            {
                case ResultState.Verified:
                    style.ForeColor = Color.Black;
                    break;

                case ResultState.Unverified:
                    style.ForeColor = Color.Gray;
                    break;

                case ResultState.VerifiedAndEmpty:
                    style.ForeColor = Color.Red;
                    break;

                default:
                    throw new ArgumentException("invalid state: " + state);
            }

            foreach (DataGridViewCell cell in rapidShareResults.Rows[rowId].Cells)
            {
                cell.Style = style;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0)
            {
                Program.OnTitleClick(rapidShareResults[e.ColumnIndex, e.RowIndex]);
            }
        }

        private void OnSelectionChanged(object sender, EventArgs e)
        {
            if (this.rapidShareResults.SelectedCells.Count > 0)
            {
                this.rapidShareResults.SelectedCells[0].Selected = false;
            }
        }

        private void OnCopyLinkClicked(object sender, EventArgs e)
        {
            if (rightClickColId >= 0 && rightClickRowId >= 0)
            {
                ResultDetails resultDetails = (ResultDetails)rapidShareResults.Rows[rightClickRowId].Cells[0].Value;
                Clipboard.SetText(resultDetails.Url);
            }
        }

        private void OnMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                rightClickRowId = e.RowIndex;
                rightClickColId = e.ColumnIndex;

                ResultDetails resultDetails = (ResultDetails)this.rapidShareResults.Rows[rightClickRowId].Cells[0].Value;
                if (string.IsNullOrEmpty(resultDetails.Password))
                {
                    RightClickMenu.Items[2].Enabled = false;
                }
                else
                {
                    RightClickMenu.Items[2].Enabled = true;
                }
            }

        }

        private void openResultLinkInBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rightClickColId >= 0 && rightClickRowId >= 0)
            {
                ResultDetails resultDetails = (ResultDetails)this.rapidShareResults.Rows[rightClickRowId].Cells[0].Value;
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName = resultDetails.Url;
                proc.Start();
            }
        }

        private void CopyPassword_Click(object sender, EventArgs e)
        {
            if (rightClickColId >= 0 && rightClickRowId >= 0)
            {
                ResultDetails resultDetails = (ResultDetails)rapidShareResults.Rows[rightClickRowId].Cells[0].Value;
                Clipboard.SetText(resultDetails.Password);
            }
        }

        private string lastSearchString = "";
        private void CompleteSearchString()
        {
            if (torecLink.Text.Length < 1)
                return;

            if (torecLink.Text.Trim().Equals(lastSearchString.Trim()))
                return;
            else
                lastSearchString = torecLink.Text;

             string reqStr = "http://www.google.com/search?q=epguides.com%20" + torecLink.Text + "&btnI=745";
            WebResponse resp = NetworkServices.NetworkServices.SendGetRequest(reqStr, false, ""); //(reqStr, "Accept-Encoding: gzip, deflate", "Cookie: PREF=ID=c4a62c0f73d2a4b8:LD=en:NR=10:TM=1227213606:LM=1228326575:GM=1:S=SJN1133k_icvzED0; NID=18=rI9cU8DLvfnoMBtyYFafhYIhVI0zLnSLU1PwkZPuL1eihxZQbPCsjFt66Ghe1ASRpAcvx5dd1glA5kNNrsciWkGxfl4k-uFbcHjuSYLrTAayd_dUEbnfc9egBBt0Hleh", "www.google.com");
            string fwdAddr = resp.Headers["Location"];
            if (fwdAddr != null)
            {
                resp = NetworkServices.NetworkServices.SendGetRequest(fwdAddr, false, "");
            }
            StreamReader sr = new StreamReader(resp.GetResponseStream());
            string s = sr.ReadToEnd();
            int EndPos = s.IndexOf("</pre>\r\n</div>");
            if (EndPos > -1)
            {
                int StartPos = s.LastIndexOf("\nSeason ", EndPos);
                if (StartPos == -1)
                    StartPos = s.LastIndexOf("\n&bull; Season ", EndPos);
                string buffer = s.Substring(StartPos, EndPos - StartPos);
                string []lines = buffer.Split(new []{"</a>"}, StringSplitOptions.RemoveEmptyEntries);

                string latestSeason = "";
                string latestEpisode = "";
                int age=0;
                foreach (string line in lines)
                {
                    Regex regex =
                        new Regex(@".+([0-9]{1,2})\-([ 0-9][0-9]).+([1-9 ][0-9][ /]\w+[ /][0-9]{2}).+");
                    Match m = regex.Match(line);
                    if (!m.Success)
                        continue;
                    string dateString = m.Groups[3].Value;
                    DateTime dt;
                    if (DateTime.TryParse(dateString, out dt))
                    {
                        if (dt > DateTime.Now)
                        {
                            break;
                        }
                        latestSeason = m.Groups[1].Value.Trim();
                        latestEpisode = m.Groups[2].Value.Trim();
                        age = (int) DateTime.Now.Subtract(dt).TotalDays;
                    }

                }

                if (latestSeason.Length == 1)
                    latestSeason = "0" + latestSeason;
                if (latestEpisode.Length == 1)
                    latestEpisode = "0" + latestEpisode;

                string latestSeasonEpisode = " S" + latestSeason + "E" + latestEpisode;
                //torecLink.Text += latestSeasonEpisode;
                //torecLink.Select(torecLink.Text.IndexOf(latestSeasonEpisode), latestSeasonEpisode.Length);
                int titlePos = s.IndexOf("<title>") + "<title>".Length;
                int titleEndPos = s.IndexOf("</title>", titlePos);
                int altTitlePos = s.IndexOf("(");
                if (altTitlePos >= 0 && altTitlePos < titleEndPos)
                    titleEndPos = altTitlePos;
                string title = s.Substring(titlePos, titleEndPos - titlePos);

/*                torecLink.AutoCompleteMode = AutoCompleteMode.Append;
                torecLink.AutoCompleteSource = AutoCompleteSource.CustomSource;
                AutoCompleteStringCollection sc = new AutoCompleteStringCollection();
                sc.Add(title + latestSeasonEpisode);
                torecLink.AutoCompleteCustomSource = sc;
                SendKeys.Send(" ");*/
                torecLink.Text = title + latestSeasonEpisode;

                toolStripStatusLabel.Text = "Found " + title + latestSeasonEpisode + " (" + age + " days old)";
                
            }
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F8)
            {
                CompleteSearchString();
            }
        }

        private void ConfButton_Click(object sender, EventArgs e)
        {
            ShowConfigurationScreen();
        }

        public void ShowConfigurationScreen()
        {
            Configuration configuration = new Configuration();
            configuration.ShowDialog();
        }

        private void copyLinksToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rightClickColId >= 0 && rightClickRowId >= 0)
            {
                ResultDetails resultDetails = (ResultDetails)rapidShareResults.Rows[rightClickRowId].Cells[0].Value;
                String s = "";

                foreach (string link in resultDetails.Links)
                {
                    s += link + "\r\n";
                }

                Clipboard.SetText(s);
            }
        }
    }
}